package com.link.play.fit.ai.ui.vip

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.CountDownTimer
import androidx.lifecycle.lifecycleScope
import com.android.billingclient.api.ProductDetails
import com.bumptech.glide.Glide
import com.link.play.fit.ai.R
import com.link.play.fit.ai.RemoteConfig
import com.link.play.fit.ai.RemoteConfig.vipProductYearDiscount
import com.link.play.fit.ai.base.BaseActivity
import com.link.play.fit.ai.databinding.AcVipDiscountNewLayoutBinding
import com.link.play.fit.ai.ext.d
import com.link.play.fit.ai.kv.AuthCache.FIRBASE_SUB_PRODUCT_ID
import com.link.play.fit.ai.kv.AuthCache.SUB_CURRENCY
import com.link.play.fit.ai.kv.AuthCache.SUB_PRICE_VALUE
import com.link.play.fit.ai.kv.AuthCache.SUB_PRODUCT_ID
import com.link.play.fit.ai.utils.GooglePayUtil
import com.link.play.fit.ai.utils.GooglePayUtil.defaultDiscountYearPrice
import com.link.play.fit.ai.utils.GooglePayUtil.defaultYearPrice
import com.link.play.fit.ai.utils.GooglePayUtil.extractAndCalculateDailyPriceToMonth
import com.link.play.fit.ai.utils.GooglePayUtil.google_pay_id
import com.link.play.fit.ai.utils.GooglePayUtil.parsePriceString
import com.link.play.fit.ai.utils.OpenAgreementUtils
import com.link.play.fit.ai.utils.PriceUtils.calculatePercentage
import kotlinx.coroutines.launch
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import kotlin.random.Random

class VipDiscountAc :
    BaseActivity<AcVipDiscountNewLayoutBinding>(AcVipDiscountNewLayoutBinding::inflate) {
    private var subscriptionOfferDetails: List<ProductDetails.SubscriptionOfferDetails>? = null
    private var productDetails: ProductDetails? = null
    private var formattedPrice = ""
    private var yearFormattedPrice = ""
    private var isGuide = false

    // 倒计时总时长（5分钟 = 300秒 = 300,000毫秒）
//    private val totalTime = 300_000L
//    private var countDownTimer: CountDownTimer? = null
//    private lateinit var countDownTimer: CountDownTimer
//    private val totalTimeInMillis = 24 * 60 * 60 * 1000L

    // 倒计时总时长（5分钟 = 300秒 = 300,000毫秒）
    private val totalTime = 300_000L
    private var countDownTimer: CountDownTimer? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        isGuide = intent.extras?.getBoolean("isGuide") ?: false
        SUB_PRODUCT_ID = vipProductYearDiscount
        FIRBASE_SUB_PRODUCT_ID = vipProductYearDiscount
        google_pay_id = vipProductYearDiscount

        binding.priceValueText.text =  extractAndCalculateDailyPriceToMonth(defaultDiscountYearPrice)
        binding.monthsforText.text = getString(
            R.string.months_for_value,defaultDiscountYearPrice
        )
        val dem = calculatePercentage(defaultYearPrice, defaultDiscountYearPrice, 0)
        binding.discountText.text = dem
        EventBus.getDefault().register(this)

        yearFormattedPrice = intent.getStringExtra("originalPrice").toString()

        Glide.with(this).asGif().load(R.drawable.hahaha).into(binding.ivGif)
        initListener()

        binding.subscroptionText.setOnClickListener {
            "subscriptionOfferDetails $subscriptionOfferDetails".d()
            subscriptionOfferDetails?.forEach {
                SUB_CURRENCY = it.pricingPhases.pricingPhaseList[0].priceCurrencyCode
                SUB_PRICE_VALUE = parsePriceString(it.pricingPhases.pricingPhaseList[0].formattedPrice)
                GooglePayUtil.pay(this, it.offerToken, productDetails!!)
            }
        }
        startCountDown()
        binding.disText2.text = getString(
            R.string.become_one_of,"${Random.nextInt(1_000_000, 1_777_778)}"
        )
    }

    @SuppressLint("DefaultLocale", "StringFormatMatches")
    private fun initListener() {
        binding.countLayout.setOnClickListener {
            "subscriptionOfferDetails $subscriptionOfferDetails".d()
            subscriptionOfferDetails?.forEach {
//                if (it.basePlanId == SUB_YEAR_DISCOUNT_PLAN_ID) {
                SUB_CURRENCY = it.pricingPhases.pricingPhaseList[0].priceCurrencyCode
                SUB_PRICE_VALUE = parsePriceString(it.pricingPhases.pricingPhaseList[0].formattedPrice)

                GooglePayUtil.pay(this, it.offerToken, productDetails!!)
//                }
            }
        }
        binding.flClose.setOnClickListener {
            finish()
            if (RemoteConfig.noVipCanIn){
                EventBus.getDefault().post("noVipCanIn")
            }
        }
        binding.termsText.setOnClickListener {
            OpenAgreementUtils.openTerms(this)
        }
        binding.privacyText.setOnClickListener {
            OpenAgreementUtils.openPrivacy(this)
        }
        lifecycleScope.launch {
            productDetails = GooglePayUtil.queryProduct(vipProductYearDiscount)
            subscriptionOfferDetails = productDetails?.subscriptionOfferDetails
            productDetails?.subscriptionOfferDetails?.forEach {
                val pricingPhase = it.pricingPhases.pricingPhaseList[0]
//                when (it.basePlanId) {
//                    SUB_YEAR_DISCOUNT_PLAN_ID -> {
                formattedPrice = pricingPhase.formattedPrice
                binding.priceValueText.text =  extractAndCalculateDailyPriceToMonth(formattedPrice)

                binding.monthsforText.text = getString(
                    R.string.months_for_value,formattedPrice
                )
//                binding.atAnyText.text = getString(
//                    R.string.you_can_unsubscribe2, formattedPrice
//                )
                "yearFormattedPrice $yearFormattedPrice  formattedPrice $formattedPrice".d()
                val dem = calculatePercentage(yearFormattedPrice, formattedPrice, 0)
                binding.discountText.text = dem
//                    }

//                    else -> {}
//                }
            }
//            productDetails?.subscriptionOfferDetails?.forEach {
//                val pricingPhase = it.pricingPhases.pricingPhaseList[0]
////                when (it.basePlanId) {
////                    SUB_YEAR_DISCOUNT_PLAN_ID -> {
//                        formattedPrice = pricingPhase.formattedPrice
//                        binding.onlyText.text = getString(
//                            R.string.only_text,
//                            extractAndCalculateDailyPriceToWeek(formattedPrice)
//                        )
//                        binding.atAnyText.text = getString(
//                            R.string.you_can_unsubscribe2, formattedPrice
//                        )
//                        "yearFormattedPrice $yearFormattedPrice  formattedPrice $formattedPrice".d()
//                        val dem = calculatePercentage(yearFormattedPrice, formattedPrice, 0)
//                        binding.discountText.text = getString(
//                            R.string.discount_text22,
//                            dem
//                        )
////                    }
////                    else -> {}
////                }
//            }
        }

    }


//    private fun startCountDown() {
//        countDownTimer = object : CountDownTimer(totalTimeInMillis, 1000) {
//            override fun onTick(millisUntilFinished: Long) {
//                updateTimeDisplay(millisUntilFinished)
//            }
//
//            override fun onFinish() {
//                // 倒计时结束处理
////                findViewById<TextView>(R.id.tv_seconds).text = "00"
//            }
//        }.start()
//    }

    private fun startCountDown() {
        countDownTimer?.cancel() // 防止重复启动

        countDownTimer = object : CountDownTimer(totalTime, 1000) {
            override fun onTick(millisUntilFinished: Long) {
                // 将剩余时间转为分钟和秒（两位显示）
                val minutes = (millisUntilFinished / 1000) / 60
                val seconds = (millisUntilFinished / 1000) % 60

                binding.minText.text = String.format("%02d", minutes)  // 如 "04"
                binding.secText.text = String.format("%02d", seconds)  // 如 "59"
            }

            override fun onFinish() {
                // 倒计时结束处理
                binding.minText.text = "00"
                binding.secText.text = "00"

            }
        }.start()
    }

    /**
     * 将毫秒转换为时分秒并更新UI
     */
    private fun updateTimeDisplay(millis: Long) {
        val hours = (millis / 3600000).toInt()
        val minutes = (millis % 3600000 / 60000).toInt()
        val seconds = (millis % 60000 / 1000).toInt()

        binding.hourText.text = String.format("%02d", hours)
        binding.minText.text = String.format("%02d", minutes)
        binding.secText.text = String.format("%02d", seconds)
    }


    override fun onDestroy() {
        super.onDestroy()
        countDownTimer?.cancel()

        EventBus.getDefault().unregister(this)
    }

    @SuppressLint("SetTextI18n")
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageEvent(event: String) {
        if (event == "isVip") {
            finish()
        }
    }


}
